package com.zoffy.oj_backend.judge.codesandbox.utils;


import com.zoffy.oj_backend.judge.codesandbox.model.ExecuteMessage;
import com.zoffy.oj_backend.model.enums.JudgeInfoMessageEnum;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ProcessUtil {
    public static ExecuteMessage runProcessAndGetMessage(Process process) throws InterruptedException, IOException {
        ExecuteMessage executeMessage = new ExecuteMessage();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        int exitCode = process.waitFor();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        List<String> outputList = new ArrayList<>();
        String compileOutputLine;
        while ((compileOutputLine = bufferedReader.readLine()) != null) {
            outputList.add(compileOutputLine);
        }
        executeMessage.setMessage(StringUtils.join(outputList, '\n'));
        executeMessage.setExitCode(exitCode);
        if (exitCode != 0) {
            BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            List<String> errorOutputList = new ArrayList<>();
            String errorOutputLine;
            while ((errorOutputLine = errorBufferedReader.readLine()) != null) {
                errorOutputList.add(errorOutputLine);
            }
            executeMessage.setErrorMessage(StringUtils.join(errorOutputList, '\n'));
        }
        stopWatch.stop();
        executeMessage.setTime(stopWatch.getTotalTimeMillis());
        return executeMessage;
    }
}
